<template>
  <!-- 月计划变更编辑 -->
  <div class="e-form">
    <div class="tabs" v-if="Object.keys(basicFormData).length != 0">
      <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
        <!-- 基本信息 -->
        <el-tab-pane
          label="基本信息"
          name="baseInfo"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="物资明细"
          name="goodsAndMaterials"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="附件信息"
          name="accessory"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <div>
          <!-- 基本信息 -->
          <div id="baseInfoCon" class="con">
            <div class="e-form">
              <BillTop title="月计划变更编辑" @cancel="handleClose"></BillTop>
              <div class="tabs">
                <div class="tabs-title" id="baseInfo">基本信息</div>
                <div style="width: 100%" class="form">
                  <el-form
                    :model="basicFormData"
                    label-width="150px"
                    :rules="rules"
                    ref="basicFormData"
                    class="demo-ruleForm"
                  >
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="月变更编号：">
                          {{ basicFormData.billNo }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="单据机构：">
                          {{ basicFormData.orgName }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="计划年度：">
                          {{ basicFormData.year }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="计划月份：">
                          {{ basicFormData.month }}
                        </el-form-item>

                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="不含税计划金额(元)：">
                          {{ basicFormData.amountChanged }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="原计划金额(元)：">
                          {{ basicFormData.totalAmount }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="税率%：" prop="taxRateChanged">
                          <el-input
                            placeholder="请填写"
                            @blur="countTaxAmount"
                             @input="taxRateinput"
                            v-model="basicFormData.taxRateChanged"
                            v-enter-float="{
                                    set: this,
                                    val: 'basicFormData',
                                    key: 'taxRateChanged'
                                }"
                          ></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="税额：" prop="taxAmountChanged">
                          <el-input
                            placeholder="请填写"
                            v-model="basicFormData.taxAmountChanged"
                          ></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="变更后计划金额(元)：">
                          {{basicFormData.totalAmountChanged}}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                         <el-form-item label="变更日期：" prop="planDate">
                          <el-date-picker
                            v-model="basicFormData.planDate"
                            type="date"
                            placeholder="选择日期"
                            :clearable="false"
                          >
                          </el-date-picker>
                        </el-form-item>
                        <!-- <el-form-item label="填报人：">{{
                          basicFormData.preparer
                        }}</el-form-item> -->
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="币种：">
                          {{ basicFormData.currency }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                         <el-form-item label="填报人：">
                          {{ basicFormData.preparer }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                      <el-form-item label="变更期数：">
                        {{ basicFormData.period }}
                      </el-form-item>
                      </el-col>
                      <el-col :span="12">
                         <el-form-item
                          label="状态："
                          v-model="basicFormData.state"
                        >
                          {{
                            ["草稿", "审核中", "已审核", "已关闭",'', "已作废"][
                              basicFormData.state
                            ]
                          }}
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-form-item label="备注：">
                        <el-input
                          type="textarea"
                          :rows="2"
                          placeholder="请输入内容"
                          v-model="basicFormData.remarks"
                        >
                        </el-input>
                      </el-form-item>
                    </el-row>

                    <el-row>
                      <el-form-item label="本位币：">
                        {{ basicFormData.baseCurName }}
                      </el-form-item>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <!-- <el-form-item label="计划金额（本位币）：">
                          {{basicFormData.baseCurAmount}}

                        </el-form-item> -->
                        <el-form-item label="本位币汇率：">
                          {{ basicFormData.baseCurRate }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">

                      </el-col>
                    </el-row>
                  </el-form>
                </div>
              </div>
            </div>
          </div>

          <!-- 物资明细 -->
          <div id="goodsAndMaterialsCon" class="con">
            <div class="tabs-title" id="goodsAndMaterials">物资明细</div>
            <div class="e-table">
              <div class="top">
                <div class="left">
                  <div>
                    <el-button
                      size="small"
                      style="background: rgb(75, 178, 255); color: #fff"
                      @click="yearPlanBtn()"
                      >年计划引入</el-button
                    >
                  </div>
                </div>
                 <div class="right">
                <div class="squarecolor">
                    <div class="color colorAdds"></div>
                    <span>新增</span>
                </div>

                <div class="squarecolor">
                    <div class="color colorDel"></div>
                    <span>删除</span>
                </div>
                <div class="squarecolor item">
                    <div class="color colorUpdate"></div>
                    <span>修改</span>
                </div>
            </div>
              </div>
              <el-table
              class="table"
                :data="materialsDetailList"
                border
                style="width: 100%"
                @selection-change="planTableSelect"
                :row-class-name="tableRowClass"
                :cell-class-name="cellClsNm"
                :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                :tree-props="{
                  children: 'children',
                  hasChildren: 'hasChildren',
                }"
                row-key="uuid"
                :max-height="$store.state.tableHeight"
                 ref="table"
                v-sortTable="{ 'tableData': materialsDetailList, '_this': this, 'ref': 'table' }"
              >

                <el-table-column
                  label="操作"
                  fixed
                  width="100px"
                  align="left"
                >
                  <template slot-scope="{ row, $index }">
                    <i
                      class="el-icon-delete"
                      style="cursor: pointer; font-size: 20px; color: red"

                      @click="deleteEle(row)"
                      v-if="$index > 0"
                    ></i>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="materialClassName"
                  label="类别"
                  min-width="200"
                  align="left"
                >

                </el-table-column>
                <el-table-column
                  prop="materialName"
                  label="物资名称"
                  width="200"
                >
                </el-table-column>
                <el-table-column prop="spec" label="规格型号" width="100">
                </el-table-column>
                <el-table-column prop="unit" label="计量单位" width="100">
                </el-table-column>
                <el-table-column prop="texture" label="材质" width="100">
                </el-table-column>
                <el-table-column
                  prop="quantity"
                  label="数量"
                  width="100"

                >
                </el-table-column>
                <el-table-column
                  prop="price"
                  label="单价（元）"
                  width="100"

                >
                </el-table-column>
                <el-table-column
                  prop="amount"
                  label="金额（元）"
                  width="100"
                >
                  <!-- 系统默认计算，即计划数量*市场单价，不可编辑，金额累计保留2位小数，采用四舍五入方式。-->
                </el-table-column>
                 <el-table-column
                  prop="purchasingUnitName"
                  label="采购单位"
                  width="100"
                >

                </el-table-column>

                <el-table-column
                  prop="purchaseType"
                  label="采购方式"
                  width="150"
                >
                <template slot-scope="{ row }">
                      <span>{{
                      ["普通采购"][row.purchaseType]
                      }}</span>
                  </template>
                </el-table-column>
                 <el-table-column prop="quantityChanged" width="150">
                     <template slot="header">
                                        <div class="tab-header">数量<span class="tab-heade-icon">变</span></div>
                                    </template>
                  <template slot-scope="{ row, $index }">
                    <el-input
                         v-enter-float2="{
                          set: row,
                          key: 'quantityChanged'
                      }"
                      @input="input(row)"
                      @blur="amount"
                      v-model="row.quantityChanged"
                      style="width:100px"
                      clearable
                      v-if="$index > 0"
                    ></el-input>
                  </template>
                </el-table-column>
                 <el-table-column prop="priceChanged" width="150">
                     <template slot="header">
                                        <div class="tab-header">单价(元)<span class="tab-heade-icon">变</span></div>
                                    </template>
                  <template slot-scope="{ row, $index }">
                    <el-input
                         v-enter-float="{
                          set: row,
                          key: 'priceChanged'
                      }"
                      @input="input(row)"
                      @blur="amount"
                      v-model="row.priceChanged"
                      style="width:100px"
                      clearable
                      v-if="$index > 0"
                    ></el-input>
                  </template>
                </el-table-column>
                  <el-table-column prop="amountChanged" width="150">
                     <template slot="header">
                                        <div class="tab-header">金额(元)<span class="tab-heade-icon">变</span></div>
                                    </template>

                </el-table-column>
                  <el-table-column
                  prop="purchasingUnitNameChanged"
                  width="200"
                >
                 <template slot="header">
                   <div class="tab-header">采购单位<span class="tab-heade-icon">变</span></div>
                   <i slot="suffix" class="el-input__icon el-icon-document-copy" style=" cursor: pointer;" @click="selectPurchasingUnitName()"></i>
                   </template>
                     <template slot-scope="{ row,$index  }">
                  <el-input
                    @input="input(row)"
                    v-model="row.purchasingUnitNameChanged"
                      v-if="$index > 0"
                  >
                  <i slot="suffix" class="el-input__icon el-icon-document-copy" style=" cursor: pointer;" @click="selectPurchasingUnitNames(row)"></i>
                  </el-input>
                </template>
                </el-table-column>
                <el-table-column
                  prop="purchaseTypeChanged"
                  width="200"

                >
                    <template slot="header">
                   <div class="tab-header">采购方式<span class="tab-heade-icon">变</span></div>
                    <i slot="采购方式" class="el-input__icon el-icon-document-copy"  style=" cursor: pointer;" @click="selectPurchaseType()"></i>
                   </template>
                  <template slot-scope="{ row,$index  }">
                      <el-select v-model="row.purchaseTypeChanged" placeholder="请选择" v-if="$index > 0" @change="selectProcurementMethod(row)">
                          <el-option
                            v-for="item in procurementMethod"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                    </el-select>
                    </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <!-- 附件信息 -->
          <div id="accessoryCon" class="con">
            <div class="tabs-title" id="accessory">附件信息</div>
            <attach-comp
              :relationId="attachId"
              bucketName="material"
              v-if="objFlag.flag5"
            />
            <div class="seize-a-seat" v-else>
              <i class="el-icon-loading"></i>
            </div>
          </div>
           <!-- 审核历史 -->
           <div id="auditHistoryCon" class="con">
              <div class="tabs-title" id="auditHistory">审核历史</div>
              <div class="e-table">
                  <ComAuditHistoryIndex
                      :tableData.sync="auditHistoryTable"
                      @getAuditHistory="getAuditHistory"
                      ref="AuditHistoryRef"
                  />
              </div>
          </div>
        </div>
      </el-tabs>
    </div>
    <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    <div class="buttons">
      <span class="tip"
        ><span style="color: red; margin-right: 0">*</span>为必填项</span
      >

      <el-button
        type="primary"
        size="small"
        style="background: #2e61d7"
        v-if="basicFormData.state === '1' || basicFormData.state === '2'"
        >打印</el-button
      >
      <ComExaButtons
                v-if="basicFormData.state != 5"
                :auditState="auditState"
                :state="basicFormData.state"
                 :founderId="founderId"
                @exas="exas"
            />

      <!-- <el-button
        type="primary"
        size="small"
        style="background: #2e61d7"
        @click="audit"
        v-if="basicFormData.state === '1'"
        >审核</el-button
      >
      <el-button
        type="primary"
        size="small"
        style="background: #2e61d7"
        v-if="basicFormData.state === '0'"
        @click="save('basicFormData')"
        >保存</el-button
      >
      <el-button
        type="primary"
        size="small"
        style="background: #2e61d7"
        v-if="basicFormData.state === '0'"
        @click="submit('basicFormData')"
        >保存并提交</el-button
      >
      <el-button
        type="primary"
        size="small"
        style="background: #2e61d7"
        v-if="basicFormData.state === '1'"
        @click="undoAudit"
        >撤回</el-button
      >
      <el-button
        type="danger"
        size="small"
        @click="ctDelete"
        v-if="basicFormData.state === '0'"
        >删除</el-button
      >
      <el-button
        type="primary"
        size="small"
        style="background: #2e61d7"
        v-if="basicFormData.state === '1'"

        >作废</el-button
      > -->
      <el-button size="small" @click="handleClose">取消</el-button>
    </div>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
import { selectDataClient, getUuid } from '@/utils/common'
import ComAuditHistoryIndex from '@/pages/materialsmanagement/components/auditHistory/auditHistoryIndex'
import AttachComp from '@/components/common/attachIndex'
import request from '@/api/materials/plan.js'
import monthPlanApi from '@/api/materials/monthPlan.js'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            userName: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },
            tableData: [],
            auditState: {}, //按钮状态
            materialsDetailList: [], //明细
            auditHistoryTable: [], //审核历史
            value: '',
            textarea: '',
            formData: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                'amount': 0,
                'amountChanged': 0,
                'baseCurAmount': 0,
                'baseCurAmountChanged': 0,
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'baseCurTaxAmount': 0,
                'baseCurTaxAmountChanged': 0,
                'baseCurTotalAmount': 0,
                'baseCurTotalAmountChanged': 0,
                'billId': '',
                'billNo': '',
                'currency': '',
                'currencyId': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'month': 0,
                'monthPlanBillId': '',
                'monthPlanBillNo': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'period': 0,
                'planDate': '',
                'preparer': '',
                'preparerId': '',
                'remarks': '',
                'rmbAmount': 0,
                'rmbAmountChanged': 0,
                'rmbId': '',
                'rmbName': '',
                'rmbRate': 0,
                'rmbTaxAmount': 0,
                'rmbTaxAmountChanged': 0,
                'rmbTotalAmount': 0,
                'rmbTotalAmountChanged': 0,
                'state': '',
                'taxAmount': 0,
                'taxAmountChanged': 0,
                'taxRate': 0,
                'taxRateChanged': 0,
                'totalAmount': 0,
                'totalAmountChanged': 0,
                'workId': '',
                'year': 0,
                'yearPlanBillId': '',
                'yearPlanBillNo': ''
            },
            objFlag: {
                flag5: false,
            },
            //验证
            rules: {
                planDate: [
                    { required: true, message: '请输入变更日期', trigger: 'change' },
                ],
                taxRateChanged: [{ required: true, message: '请填写税率', trigger: 'change' }],
                taxAmountChanged: [
                    { required: true, message: '请填写税额', trigger: 'change' },
                ],

                remarks: [{ required: true, message: '请填写备注', trigger: 'change' }],
            },
            procurementMethod: [{
                value: 0,
                label: '邀请招标'
            }, {
                value: 1,
                label: '公开招标'
            }, {
                value: 2,
                label: '询价'
            }, {
                value: 3,
                label: '竞争性谈判'
            }, {
                value: 4,
                label: '单一性来源'
            },
            {
                value: 5,
                label: '甲控（业主招标）'
            }],
            moneyList: [], //币种
            orgId: '', //机构id
            orgName: '', //机构名称
            planSelect: [], //明细用户选择的值
            billid: '',
            isSkip: false, //是否跳转
            params: {
                'billId': this.$route.query.billid, //单据Id  ***
                'billType': '10031', //单据编码  ***
                'dtls': [], //审核中字段值变更历史
                'freeNextUnitIndex': 0, //下一步审核步骤
                'freeNextUser': '', //下一步审核人ID
                'isPass': true, //审核是否通过
                'isShareInAudit': true, //是否共享审核节点
                'opinion': '', //审核意见   ***
                'orgId': this.orgId, //单据机构Id
                'orgName': this.orgName, //单据机构名称
                'userId': this.userId, //审核人Id    ***
                'workId': '', //流程Id
            }
        }
    },
    computed: {

        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billid
        },
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.billid = this.$route.query.billid
        this.founderId = localStorage.getItem('userId')
        this.getBasicData() //进入页面就获取基本信息数据
        this.getYearPlanListDetail() //获取明细
        this.getAttach()
        this.getAuditHistory()
        this.getCurrentUnitInfo()
    },
    mounted () {
    // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'goodsAndMaterials', 'accessory', 'auditHistory']
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    methods: {
        ...mapMutations(['setPopConfirm', 'setSelectedInfo']),

        // 获取按钮状态
        getCurrentUnitInfo () {
            request
                .getCurrentUnitInfo({
                    billId: this.$route.query.billid,
                    billType: 10031,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                .then(res => {
                    this.auditState = res
                })
        },
        // 按钮组件触发事件
        exas (data) {
            switch (data) {
            case 'audit':
                this.audit() //审核
                break
            case 'undoAudit':
                this.undoAudit() //撤回
                break
            case 'submitCommit':
                this.submit() //提交
                break
            case 'submit':
                this.save() //保存
                break
            case 'nullify':
                this.nullify() //作废
                break
            case 'deleteData':
                this.ctDelete() //删除
                break
            default:
                break
            }
        },
        //验证税率
        taxRateinput () {
            if(this.basicFormData.taxRateChanged > 100) {
                this.basicFormData.taxRateChanged = 0
            }
        },
        //年计划引入按钮
        yearPlanBtn () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/material/yearPlan/getListByOrgIdForSelect',
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify(
                    {
                        'orgId': this.orgId, //机构id 非必填
                        'parentId': '0', //父级id 必填
                        'year': this.basicFormData.year//计划年度 必填
                    }
                ),
                Title: '选择计划明细'
            })
                .then(val=>{
                    this.setSelectedInfo(val)

                    if(this.materialsDetailList.length > 0) {
                        val.forEach(e=>{
                            this.materialsDetailList.forEach(a=>{
                                const  Isrepeat =  a.children.some(b=>{
                                    return b.materialName == e.materialName && b.spec == e.spec
                                })
                                if(Isrepeat) {
                                    this.clientPop('info', `物资明细不允许重复,物资类别:${e.materialClassName},物资名称:${e.materialName},规格:${e.spec},材质:${e.texture},请检查!`)
                                }else{
                                    e.materialClassNameArr = e.materialClassName.split('/')
                                    e.materialClassIdArr = e.materialClassId.split('/')
                                    e.materialClassNameArr.shift()
                                    e.materialClassIdArr.shift()
                                    const obj = {
                                        uuid: getUuid(),
                                        customId: getUuid(),
                                        billId: this.billid, //	物资月度计划id
                                        billNo: this.basicFormData.billNo,
                                        amount: 0, //	金额(元)
                                        amountChanged: '', //变更后金额(元)
                                        changeType: 1, //	变更类型
                                        dtlId: '', //物资月度计划变更明细id
                                        materialClassId: e.materialClassIdArr.join('/'),
                                        materialClassName: e.materialClassNameArr.join('/'),
                                        materialId: e.materialId, //	物资id
                                        materialName: e.materialName, //	物资名称
                                        monthPlanDtlId: '', //	物资月度计划明细id
                                        price: 0, //	单价(元)
                                        priceChanged: 0, //	变更后单价(元)
                                        purchaseType: null, //	采购方式
                                        purchaseTypeChanged: null, //变更后采购方式
                                        purchasingUnitId: '', //采购单位id
                                        purchasingUnitIdChanged: '', //	变更后采购单位id
                                        purchasingUnitName: '', //	采购单位名称
                                        purchasingUnitNameChanged: '', //	变更后采购单位名称
                                        quantity: e.quantity, //	数量
                                        quantityChanged: 0, //	变更后数量
                                        spec: e.spec, //	规格型号
                                        texture: e.texture, //	材质
                                        unit: e.unit, //	计量单位
                                        yearPlanDtlId: '', //物资年度计划明细id
                                    }
                                    a.children.push(obj)
                                }
                            })
                        })

                    }else{
                        const mapObj = {}
                        let arr = []
                        val.forEach(e => {
                            const children = []
                            e.materialClassNameArr = e.materialClassName.split('/')
                            e.materialClassIdArr = e.materialClassId.split('/')
                            // TODO: 统计小计
                            let obj
                            const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                            const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                            if (!mapObj[topClassId]) {
                                obj = {
                                    topClassId,
                                    topClassName,
                                    customId: topClassId,
                                    materialClassId: topClassId,
                                    materialClassName: topClassName,
                                    uuid: getUuid(),
                                    totalAmount: '',
                                    totalQuantity: '',
                                }
                                //这里需要改成push多个对象   还没改
                                arr.push(obj)

                                mapObj[topClassId] = obj
                            } else {
                                obj = mapObj[topClassId]
                            }

                            // 物资名称
                            children.push({
                                uuid: getUuid(),
                                customId: getUuid(),
                                billId: this.billid,
                                billNo: this.basicFormData.billNo,
                                amount: 0, //	金额(元)
                                amountChanged: '', //变更后金额(元)
                                changeType: 1, //	变更类型
                                dtlId: '', //物资月度计划变更明细id
                                materialClassId: e.materialClassIdArr.join('/'),
                                materialClassName: e.materialClassNameArr.join('/'),
                                materialId: e.materialId, //	物资id
                                materialName: e.materialName, //	物资名称
                                monthPlanDtlId: '', //	物资月度计划明细id
                                price: 0, //	单价(元)
                                priceChanged: 0, //	变更后单价(元)
                                purchaseType: null, //	采购方式
                                purchaseTypeChanged: null, //变更后采购方式
                                purchasingUnitId: '', //采购单位id
                                purchasingUnitIdChanged: '', //	变更后采购单位id
                                purchasingUnitName: '', //	采购单位名称
                                purchasingUnitNameChanged: '', //	变更后采购单位名称
                                quantity: e.quantity, //	数量
                                quantityChanged: 0, //	变更后数量
                                spec: e.spec, //	规格型号
                                texture: e.texture, //	材质
                                unit: e.unit, //	计量单位
                                yearPlanDtlId: '', //物资年度计划明细id
                            })
                            obj.children = !obj.children
                                ? children
                                : obj.children.concat(children)
                            // 统计小计
                            const count = obj.children.reduce(
                                (prev, c) => (prev += c.amount || 0),
                                0
                            )
                            obj.materialName = `小计： ${count}`
                            obj.children = this.uniqueArray(obj.children, 'customId')
                        })
                        this.materialsDetailList = arr

                    }
                })
        },
        //计算明细 金额
        amount () {
            let num = 0
            this.materialsDetailList.forEach(a=>{
                a.children.forEach(item=>{
                    item.amountChanged = item.quantityChanged * item.priceChanged
                    num += item.amountChanged
                    item.amountChanged = item.amountChanged.toFixed(2)
                    this.basicFormData.amountChanged = num
                    this.basicFormData.amountChanged = this.basicFormData.amountChanged.toFixed(2)

                })
                a.materialName = `小计:${num.toFixed(2)}`
            })
            this.countTaxAmount()
        },
        //计算税额
        countTaxAmount () {
            let num = 0
            this.materialsDetailList.forEach(a=>{
                a.children.forEach(item=>{
                    if(item.changeType != -1) {
                        item.amountChanged = item.quantityChanged * item.priceChanged
                        item.amountChanged = item.amountChanged.toFixed(2)
                        num += Number(item.amountChanged)
                        this.basicFormData.taxAmountChanged =  (num * this.basicFormData.taxRateChanged) / 100
                        this.basicFormData.taxAmountChanged = this.basicFormData.taxAmountChanged.toFixed(2)
                        this.collecttotalAmount()
                    }
                })
            })
        },
        //汇总计划金额 保留2位小数，不含税计划金额+税额。
        collecttotalAmount () {
            this.basicFormData.totalAmountChanged =  Number(this.basicFormData.amountChanged) +  Number(this.basicFormData.taxAmountChanged)
            this.basicFormData.totalAmountChanged = this.basicFormData.totalAmountChanged.toFixed(2)
        },

        //选择采购单位  批量选择
        selectPurchasingUnitName () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/hr/org/getAllOrgPage', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                Title: '选择机构' // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)

                    val.forEach(b=>{
                        // row.purchasingUnitIdChanged = b.orgId
                        // row.purchasingUnitNameChanged = b.orgName
                        this.materialsDetailList.forEach(item=>{
                            item.children.forEach(a=>{
                                if(a.changeType === 1) {
                                    a.changeType = 1
                                }else{
                                    a.changeType = 2
                                }
                                a.purchasingUnitIdChanged = b.orgId
                                a.purchasingUnitNameChanged = b.orgName
                            })
                        })
                    })

                })

        },
        //选择采购单位  单个选择
        selectPurchasingUnitNames (row) {
            console.log('row', row)
            let ids = []
            selectDataClient({
                SelectServiceToken: '/hr/org/getAllOrgPage', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                Title: '选择机构' // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)
                    val.forEach(item=>{
                        if(item.changeType === 1) {
                            item.changeType = 1
                        }else{
                            item.changeType = 2
                        }
                        row.purchasingUnitIdChanged = item.orgId
                        row.purchasingUnitNameChanged = item.orgName
                        this.materialsDetailList.forEach(a=>{
                            if(a.changeType === 1) {
                                a.changeType = 1
                            }else{
                                a.changeType = 2
                            }
                            a.children.forEach(b=>{
                                b.children.forEach(c=>{
                                    if(row.dtlId === c.dtlId) {
                                        c.changeType = 2
                                        c.purchasingUnitIdChanged = item.orgId
                                        c.purchasingUnitNameChanged = item.orgName
                                    }
                                })
                            })
                        })
                    })
                })

        },
        //选择采购方式
        selectProcurementMethod (row) {

            this.materialsDetailList.forEach(item=>{
                item.children.forEach(a=>{
                    if(row.dtlId === a.dtlId) {
                        if(a.changeType === 1) {
                            a.changeType = 1
                        }else{
                            a.changeType = 2
                        }
                        // a.purchaseTypeChanged = row.purchaseTypeChanged

                    }else if(a.changeType !== 2) {
                        a.changeType = 0
                    }
                })
            })
        },
        //选择采购方式  批量
        selectPurchaseType () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/config/kv/getDicValue', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    type: 1,
                    dicName: '总计划明细采购方式',
                    dicKey: '',
                }),
                Title: '选择机构' // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)
                    // openAppClient('/showSelectedData', '选择结果', function () {

                    // })
                    val.forEach(b=>{
                        this.materialsDetailList.forEach(item=>{
                            item.children.forEach(a=>{
                                if(a.changeType === 1) {
                                    a.changeType = 1
                                }else{
                                    a.changeType = 2
                                }
                                a.purchaseTypeChanged = b.kvKey
                            })
                        })
                    })
                })
        },
        //转换采购方式匹配后端所需的格式
        purchaseTypes () {
            this.materialsDetailList.forEach(item=>{
                item.children.forEach(a=>{
                    if(a.purchaseTypeChanged === '邀请招标') {
                        a.purchaseTypeChanged = 0
                    }else if(a.purchaseTypeChanged === '公开招标') {
                        a.purchaseTypeChanged = 1
                    }else if(a.purchaseTypeChanged === '询价') {
                        a.purchaseTypeChanged = 2
                    }else if(a.purchaseTypeChanged === '竞争性谈判') {
                        a.purchaseTypeChanged = 3
                    }else if(a.purchaseTypeChanged === '单一性来源') {
                        a.purchaseTypeChanged = 4
                    }else if(a.purchaseTypeChanged === '甲控') {
                        a.purchaseTypeChanged = 5
                    }
                })
            })
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },

        //获取变更基本信息数据
        getBasicData () {
            this.$Ajax
                .httpGet({
                    url: '/material/monthPlanChanged/findById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    this.basicFormData = res
                })
        },
        //初始化变更明细
        initListData () {
            this.$Ajax
                .httpGet({
                    url: '/material/monthPlanChanged/initListData',
                    params: {
                        id: this.billid,
                    },
                })   .then(res => {
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.children.forEach(i => {
                            // i.uuid = i.dtlId
                            i.uuid = getUuid()
                        })
                        const count = item.children.reduce(
                            (prev, c) => (prev += c.amountChanged || 0),
                            0
                        )
                        item.materialName = `小计： ${count}`
                    })
                    this.materialsDetailList = res

                })
        },
        //根据年度计划变更id获取年度计划变更明细信息
        getYearPlanListDetail () {
            this.$Ajax
                .httpGet({
                    url: '/material/monthPlanChanged/getListById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    if( res.length == 0) {  //如果没有数据就初始化明细单
                        this.initListData()
                    }else{
                        res.forEach(item => {
                            item.materialClassName = item.topClassName
                            item.uuid = getUuid()
                            item.children.forEach(i => {
                                i.uuid = i.dtlId
                            })
                            const count = item.children.reduce(
                                (prev, c) => (prev += c.amountChanged || 0),
                                0
                            )
                            item.materialName = `小计： ${count}`
                        })
                        this.materialsDetailList = res

                    }
                })
        },
        //获取历史审核列表
        getAuditHistory () {
            const params = {
                billId: this.billid,
                billType: '10031',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            }
            request.getAuditHistory(params).then(res => {
                this.auditHistoryTable = res
            })
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
            document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        ctDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        //删除
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/material/monthPlanChanged/delete',
                    params: {
                        id: this.billid,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(res => {
                    if (res.code == 200) {
                        this.clientPop('suc', '删除成功', this.handleClose)
                    }
                })
        },

        //获取明细用户选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //删除物资明细
        deleteEle (row) {
            row.changeType = -1
        },
        //明细删除
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        //明细颜色
        tableRowClass ({ row }) {
            if(row.changeType == -1) {
                return 'red'
            }else if(row.changeType == 1) {
                return 'AddCol'
            }else if(row.changeType == 2) {
                return 'yellow'
            }
            // else if(row.children) {
            //     return 'warning-row'

            // }
            return ''
        },
        //明细表格  删除
        deleteMaterials () {
            this.planSelect.forEach((item, index) => {
                if (item.dtlId) {
                    item.changeType = -1
                } else {
                    this.materialsDetailList.splice(index, 1)
                }
            })
        },
        //保存
        save (formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    //基本
                    const p1 =  monthPlanApi.EditmonthPlanChanged(this.basicFormData)
                    //明细
                    this.purchaseTypes()
                    const p2 = monthPlanApi.EditmonthPlanChangedList(this.materialsDetailList)
                    Promise.all([p1, p2]).then(() => {
                        this.clientPop('suc', '保存成功！', this.$router.go(0))
                    })
                } else {
                    return false
                }
            })
        },
        //保存并提交
        submit () {
            this.purchaseTypes()
            const p1 =  monthPlanApi.EditmonthPlanChanged(this.basicFormData)
            const p2 = monthPlanApi.EditmonthPlanChangedList(this.materialsDetailList).then(res=>{
                if(res.code == 200) {
                    request.AuditCommit(this.params)
                }
            })
            Promise.all([p1, p2]).then(() => {
                this.clientPop('suc', '保存并提交成功！', this.handleClose, null, this.handleClose)
            })
        },

        //监听明细数据input事件
        input (row) {
            if(row.changeType === 1) {
                row.changeType = 1
            }else {
                row.changeType = 2
            }
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //取消
        handleClose () {
            this.dialogVisible = false
            this.$router.push('./monthPlan')
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.billid
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
    },
}
</script>

<style lang="scss" scoped>
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}

.e-table {
  background: #fff;
}
::v-deep.el-table .warning-row {
  display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 5px;
}

.el-tab-pane {
  margin-left: -10px;
}
</style>